package com.shu.school.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

public class DBUtil {
    private static final String url = "jdbc:mysql://localhost/talk?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
    private static final String user = "root";
    private static final String password="shu030320";

    /**
     * 获取数据库连接
     */
    public static Connection getConnection()  {
        // 获取连接,URL
        Connection con = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return con;
    }

    //    private static DataSource ds;// 数据源，使用连接池后替代DriverManager
//    public static Connection getConnection() throws SQLException {
//        Connection connection = null;
//        try {
//            if (ds == null) {
//                Context context = new InitialContext();
//                //获取数据源
//                ds = (DataSource) context.lookup("java:comp/env/jdbc/talks");
//            }
//            connection = ds.getConnection();
//        } catch (NamingException e) {
//            e.printStackTrace();
//        }
//        return connection;
//    }
    //释放JDBC相关资源
    public static void release(ResultSet rs, Statement st,Connection connection) {
        if (rs != null) {
            try {
                rs.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st !=null) {
            try {
                st.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection !=null) {
            try {
                connection.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws SQLException {

        System.setProperty("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
        Connection connection = DBUtil.getConnection();
        //获取数据库
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from category");
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id"+ id + "name"+ name);
        }
        //释放资源
        DBUtil.release(resultSet,statement,connection);
    }
}
